package com.mazaiting.scheduler.manager;

import com.mazaiting.scheduler.constant.SchedulerConstant;
import com.mazaiting.scheduler.domain.bean.ExecutionJobBean;
import com.mazaiting.scheduler.domain.entity.SysQuartzJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.stereotype.Component;

import java.util.Date;

import static org.quartz.TriggerBuilder.newTrigger;

/**
 * 定时任务管理者
 *
 * @author mazaiting
 * @create_time 2022/4/5 13:11
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class QuartzManager {
    /**
     * 任务名
     */
    private static final String JOB_NAME = "TASK_";

    /**
     * 调度器
     */
    private final Scheduler scheduler;

    /**
     * 添加任务
     *
     * @param quartzJob 任务
     */
    public void addJob(SysQuartzJob quartzJob) {
        try {
            // 构建job信息
            JobDetail jobDetail = JobBuilder.newJob(ExecutionJobBean.class).withIdentity(JOB_NAME + quartzJob.getId()).build();
            // 通过触发器名和 cron 表达式创建 Trigger
            Trigger cronTrigger = newTrigger().withIdentity(JOB_NAME + quartzJob.getId()).startNow().withSchedule(CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression())).build();
            // 设置数据
            cronTrigger.getJobDataMap().put(SchedulerConstant.JOB_KEY, quartzJob);
            // 重置启动时间
            ((CronTriggerImpl) cronTrigger).setStartTime(new Date());
            // 启动定时任务
            scheduler.scheduleJob(jobDetail, cronTrigger);
            // 暂停任务
            if (quartzJob.getPause()) {
                pauseJob(quartzJob);
            }
        } catch (Exception e) {
            log.error("创建定时任务失败", e);
            throw new RuntimeException("创建定时任务失败");
        }
    }

    /**
     * 更新job cron表达式
     *
     * @param quartzJob 任务
     */
    public void updateJob(SysQuartzJob quartzJob) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 如果不存在则创建一个定时任务
            if (trigger == null) {
                addJob(quartzJob);
                trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            }
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression());
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            //重置启动时间
            ((CronTriggerImpl) trigger).setStartTime(new Date());
            trigger.getJobDataMap().put(SchedulerConstant.JOB_KEY, quartzJob);

            scheduler.rescheduleJob(triggerKey, trigger);
            // 暂停任务
            if (quartzJob.getPause()) {
                pauseJob(quartzJob);
            }
        } catch (Exception e) {
            log.error("更新定时任务失败", e);
            throw new RuntimeException("更新定时任务失败");
        }

    }

    /**
     * 删除一个job
     *
     * @param quartzJob 任务
     */
    public void deleteJob(SysQuartzJob quartzJob) {
        try {
            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
            scheduler.pauseJob(jobKey);
            scheduler.deleteJob(jobKey);
        } catch (Exception e) {
            log.error("删除定时任务失败", e);
            throw new RuntimeException("删除定时任务失败");
        }
    }

    /**
     * 恢复一个job
     *
     * @param quartzJob 任务
     */
    public void resumeJob(SysQuartzJob quartzJob) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 如果不存在则创建一个定时任务
            if (trigger == null) {
                addJob(quartzJob);
            }
            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
            scheduler.resumeJob(jobKey);
        } catch (Exception e) {
            log.error("恢复定时任务失败", e);
            throw new RuntimeException("恢复定时任务失败");
        }
    }

    /**
     * 立即执行job
     *
     * @param quartzJob 任务
     */
    public void runJobNow(SysQuartzJob quartzJob) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 如果不存在则创建一个定时任务
            if (trigger == null) {
                addJob(quartzJob);
            }
            JobDataMap dataMap = new JobDataMap();
            dataMap.put(SchedulerConstant.JOB_KEY, quartzJob);
            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
            scheduler.triggerJob(jobKey, dataMap);
        } catch (Exception e) {
            log.error("定时任务执行失败", e);
            throw new RuntimeException("定时任务执行失败");
        }
    }

    /**
     * 暂停一个job
     *
     * @param quartzJob 任务
     */
    public void pauseJob(SysQuartzJob quartzJob) {
        try {
            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
            scheduler.pauseJob(jobKey);
        } catch (Exception e) {
            log.error("定时任务暂停失败", e);
            throw new RuntimeException("定时任务暂停失败");
        }
    }
}
